const db = require('../db');

class PracticeRecord {
  static async create(record) {
    const {
      userId,
      practiceDate,
      totalProblems,
      correctCount,
      accuracy,
      totalTime,
      details
    } = record;

    // 将 ISO 时间字符串转换为 MySQL DATETIME 格式
    const mysqlDateTime = new Date(practiceDate)
      .toISOString()
      .slice(0, 19)
      .replace('T', ' ');

    const sql = `
      INSERT INTO practice_records 
      (user_id, practice_date, total_problems, correct_count, accuracy, total_time, details)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `;

    const [result] = await db.query(sql, [
      userId,
      mysqlDateTime,
      totalProblems,
      correctCount,
      accuracy,
      totalTime,
      JSON.stringify(details)
    ]);

    return result;
  }

  static async findByUserId(userId) {
    const sql = `
      SELECT * FROM practice_records 
      WHERE user_id = ? 
      ORDER BY practice_date DESC
    `;
    const [rows] = await db.query(sql, [userId]);
    return rows;
  }
}

module.exports = PracticeRecord; 